<?php
namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\UserPayHistory;
use app\common\controller\Api;
use app\common\model\ActivityOrder;
use app\common\model\Transaction;
use app\common\model\User;
use fast\Random;
use think\Db;
use think\Log;

class Notify extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function index()
    {
        $data = $this->request->post();
        $this->success('success', $data);
    }

    /**
     * 支付成功
     */
    public function wx_notify()
    {
        $paytype = 'wechat';
        $type = input('type');
        $isDebug = input('debug', '0');
        if (0 == $isDebug) {
            trace('支付回调：' . json_encode(input(), 256), 'error');
            $pay = Service::checkNotify($paytype);
            if (!$pay) {
                return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
            }

            // 获取回调数据，V3和V2的回调接收不同
            $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();
        }

        try {

            if (0 == $isDebug) {
                //微信支付V3返回和V2不同
                if (Service::isVersionV3() && $paytype === 'wechat') {
                    $data = $data['resource']['ciphertext'];
                    $data['total_fee'] = $data['amount']['total'];
                }
                trace('支付回调：' . json_encode($data, 256), 'error');

                Log::record($data);
            }
            //获取支付金额、订单号
            if (1 == $isDebug) {
                $payamount = 0.03;
                $out_trade_no = 'AC20240412154956756821';
                $result_code = 'SUCCESS';
                $return_code = 'SUCCESS';
                $transaction_id = '4200002156202404122169063061';
            } else {
                $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
                $out_trade_no = $data['out_trade_no'];
                $result_code = $data['result_code'];
                $return_code = $data['return_code'];
                $transaction_id = $data['transaction_id'];
            }

            Log::record("回调成功，订单号：{$out_trade_no}，金额：{$payamount}, result_code: {$result_code}, return_code: {$return_code}, transaction_id: {$transaction_id}");

            $transaction = Transaction::where('out_trade_no', $out_trade_no)->find();
            if ($transaction) {
                if ('SUCCESS' == $result_code) {
                    $transaction->transaction_no = $transaction_id;
                    $transaction->status = 2; //支付成功
                    $transaction->save();

                    $extroInfo = json_decode($transaction->extra_info, true);
                    if ('activity' == $extroInfo['type']) {

                        $activityId = $extroInfo['id'];
                        $activity = \app\admin\model\Activity::where('id', $activityId)->find();


                        $data = [
                            'activity_id'  => $activityId,
                            'shop_id'      => $activity->user_id,
                            'buy_id'       => $extroInfo['really_user_id'], //创建活动的用户id,
                            'dre_id'       => $extroInfo['user_id'], //推荐的用户id
                            'order_no'     => $transaction->out_trade_no,
                            'money'        => $transaction->fee,
                            'pay_status'   => 2,
                            'status'       => 1,
                            'pay_time'     => time()
                        ];

                        // 获取默认地址
                        $address = Db::name('user_deliveryaddress')->where('user_id', $extroInfo['really_user_id'])->find();
                        if ($address) {
                            $data['take_over_name']    = $address['delivery_name'];
                            $data['take_over_tel']     = $address['delivery_phone'];
                            $data['take_over_district'] = $address['delivery_district'];
                            $data['take_over_address'] = $address['delivery_address'];
                        }

                        $orderModel = new ActivityOrder();
                        $orderModel->save($data);

                    } else if ('buy_merchant_role' == $extroInfo['type'] or 'renew_merchant_role' == $extroInfo['type']) {
                        $user = User::get($extroInfo['user_id']);

                        $end_time = $user->shop_end_time != '0000-00-00' ? strtotime($user->shop_end_time) : 0;
                        $end_time = $end_time < time() ? 0 : $end_time;

                        $merchant_renewal_day   = config('site.merchant_renewal_day');   // 商家续费有效期

                        $shop_end_time = $end_time > 0 ? date('Y-m-d', $end_time + $merchant_renewal_day * 86400) : date('Y-m-d', time() + $merchant_renewal_day * 86400);

                        $data = [
                            'user_id'             => $extroInfo['user_id'],
                            'pay_way'             => 1,
                            'amount'              => $transaction->fee,
                            'renewal_day'         => $merchant_renewal_day,
                            'renewal_expire_date' => $shop_end_time,
                            'pay_no'              => $out_trade_no,
                            'createtime'          => time(),
                            'updatetime'          => time(),
                        ];

                        $userHistoryModel = new UserPayHistory();
                        $userHistoryModel->save($data);

                        $user->shop_end_time = $shop_end_time;
                        $user->is_shop = 1;
                        $user->save();
                    }
                } else {
                    $transaction->transaction_no = $transaction_id;
                    $transaction->status = -1; //支付失败
                    $transaction->save();
                }
            } else {

            }
        } catch (\Exception $e) {
            Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        if (0 == $isDebug) {
            if (Service::isVersionV3()) {
                return $pay->success()->getBody()->getContents();
            } else {
                return $pay->success()->send();
            }
        }
    }

}
